package com.yuexunit.mobilenurse.module.DocAdvice.ui.fragment;


import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.DocAdvice.adapter.InjectionListAdapter;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_Injection;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.DocAdvice_OrderExec;
import com.yuexunit.mobilenurse.module.DocAdvice.bean.YXExecuteOrder;
import com.yuexunit.mobilenurse.module.DocAdvice.model.impl.InjectionModel;
import com.yuexunit.mobilenurse.module.DocAdvice.presenter.IInjectionPresenter;
import com.yuexunit.mobilenurse.module.DocAdvice.presenter.impl.InjectionPresenter;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.Act_DocAdvice;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.view.IInjectionView;
import com.yuexunit.mobilenurse.util.CreateJson;
import com.yuexunit.mobilenurse.widget.Dialog_Fail;
import com.yuexunit.mobilenurse.widget.Dialog_Pass;
import com.yuexunit.mobilenurse.widget.Dialog_Success;
import com.yuexunit.mobilenurse.widget.EmptyLayout;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;
import org.kymjs.kjframe.utils.SystemTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;


public class Frag_Injection extends KJFragment implements IInjectionView{

    @Bind(R.id.empty_layout)
    public EmptyLayout mEmptyLayout;
    @Bind(R.id.injection_list)
    public ListView injection_list;
    private BaseAdapter adapter;
    Act_DocAdvice aty;
    //病人住院号
    private  String visitno;
    //记录Log
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    LoadingDialog loadingDialog;

    IInjectionPresenter presenter;

    //来源
    boolean source;
    //位置
    private int position;
    //医嘱标识条码
    private  String barcode;

    //定时器时间
    int countTime = 3;

    Dialog_Fail.Builder builder_fail;
    Dialog_Success.Builder builder_success;

    Handler handler_noid;
    Timer time;
    TimerTask timetask;

    ArrayList<DocAdvice_Injection> docAdvice_all = new ArrayList<DocAdvice_Injection>();

    @Override
    protected View inflaterView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        aty = (Act_DocAdvice) getActivity();
        View layout = View.inflate(aty, R.layout.frag_injection,null);
        ButterKnife.bind(this, layout);
        return layout;
    }


    @Override
    protected void initWidget(View parentView) {
        super.initWidget(parentView);
        if(presenter == null)
        {
            presenter = new InjectionPresenter(this,new InjectionModel());
        }
        visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        });
        if(SystemTool.checkNet(aty)) {
            presenter.showInjectionList(visitno);
        }
        else
        {
            ViewInject.toast("网络异常，请检查网络是否连接!");
            log.error(CreateJson.LOG_JSON("", "1", PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_DEPTNO), ""));
        }
    }

    @Override
    public void showInjectionList(ArrayList<DocAdvice_Injection> list) {
        docAdvice_all = list;
        adapter = new InjectionListAdapter(Frag_Injection.this,aty,docAdvice_all);
        injection_list.setAdapter(adapter);
        mEmptyLayout.dismiss();
    }

    @Override
    public void execDialog(int status,String message) {
        switch (status) {
            case AppConfig.EXEC_DIALOG_UNPASS_EXTERNAL:
                aty.show_unpass(message);
                break;
            case AppConfig.EXEC_DIALOG_PASS_EXTERNAL:
                aty.show_pass();
                break;
            case AppConfig.EXEC_DIALOG_UNPASS_INNER:
                show_unpass(message);
                loadingDialog.dismiss();
                break;
            case AppConfig.EXEC_DIALOG_PASS_INNER:
                show_pass();
                loadingDialog.dismiss();
                break;

        }
    }

    @Override
    public void getExecData(YXExecuteOrder executeOrderData ) {
        ArrayList<DocAdvice_OrderExec> docAdvice_orderExecs = docAdvice_all.get(position).getDespensing_exec();
        for(int i =0;i<docAdvice_orderExecs.size();i++)
        {
            if(barcode.equals(docAdvice_orderExecs.get(i).getBarcode()))
            {
                docAdvice_orderExecs.get(i).setExecdate(executeOrderData.getResponse().getOrderexecinfo().getExecdate()+"");
                docAdvice_orderExecs.get(i).setExecempid(executeOrderData.getResponse().getOrderexecinfo().getExecempid());
                docAdvice_orderExecs.get(i).setExecseq(executeOrderData.getResponse().getOrderexecinfo().getExecseq());
                docAdvice_orderExecs.get(i).setExectime(executeOrderData.getResponse().getOrderexecinfo().getExectime()+"");
            }
        }
        docAdvice_all.get(position).setDespensing_exec(docAdvice_orderExecs);

        int count = 0;
        for(int i =0;i<docAdvice_orderExecs.size();i++)
        {
            if(docAdvice_orderExecs.get(i).getExecempid()==null) {
                count++;
            }
        }
        if(count >0)
        {
            docAdvice_all.get(position).setCount(docAdvice_orderExecs.size()-count+"/"+docAdvice_orderExecs.size());
            docAdvice_all.get(position).setStatus("等待注射");
        }
        else
        {
            docAdvice_all.get(position).setCount(docAdvice_orderExecs.size()-count+"/"+docAdvice_orderExecs.size());
            docAdvice_all.get(position).setStatus("已注射");
        }
        adapter.notifyDataSetChanged();
    }

    public void ExecuteOrder(final Boolean source,final String barcode,int position)
    {
        if(presenter == null)
        {
            presenter = new InjectionPresenter(this,new InjectionModel());
        }
        this.source = source;
        this.barcode = barcode;
        this.position = position;
        presenter.Execorder(source, AppConfig.VISITNO, barcode, AppConfig.NURSEID);
    }

    public void ExecuteOrder_inner(final Boolean source,final String barcode,int position)
    {
        this.source = source;
        this.barcode = barcode;
        this.position = position;
        showExecDialog();
    }

    public void show_unpass(String message)
    {
        builder_fail = new Dialog_Fail.Builder(getActivity());
        builder_fail.setMessage(message);
        builder_fail.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder_fail.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_fail.create().show();
    }

    public void showExecDialog()
    {
        builder_success = new Dialog_Success.Builder(getActivity());
        builder_success.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        loadingDialog = new LoadingDialog(aty);
                        loadingDialog.setCanceledOnTouchOutside(false);
                        loadingDialog.show();
                        presenter.Execorder(source, AppConfig.VISITNO, barcode, AppConfig.NURSEID);
                    }
                });

        builder_success.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder_success.create().show();
    }

    public void show_pass()
    {
        final Dialog_Pass.Builder dialog_pass = new Dialog_Pass.Builder(aty);
        dialog_pass.create().show();
        handler_noid = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    Log.v("time", msg.what + "");
                } else {
                    countTime = 3;
                    if (time != null) {
                        time.cancel();
                        time = null;
                    }

                    if (timetask != null) {
                        timetask.cancel();
                        timetask = null;
                    }
                    dialog_pass.dismiss();
                }
                super.handleMessage(msg);
            }

        };

        time = new Timer(true);
        timetask = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler_noid.sendMessage(msg);

            }

        };
        time.schedule(timetask, 0, 1000);
    }
}
